package main
import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"sync"
)
type Order struct{
	ID int `json:"id"`  	//订单id
	UserId string `json:"user_id"`   //用户Id
	Item string `json:"item"`   //购买的商品
	Price float64 `json:"price"` //商品价格
}
var (
	orders []Order
	nextID = 1 
	mu   sync.Mutex  //保护orders切片的并发访问
)
func main(){
	orders = append(orders,Order{ID:1,UserId:1,Item:"laptop",Price:99.01})
	orders = append(orders.Order{ID:2,UserId:1,Item:"Mouse",Price:25.50})
	//注册http处理函数
	http.HandlerFunc("/orders",handleOrders)
	http.HandleFunc("/orders/",handleOrderByID)

	//启动http服务器	
	port := 8080
	fmt.Printf("订单阿皮服务启动在端口%d...\n",port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d",port),nil))
}
// handleOrders 处理 /orders 路径的请求 (GET 和 POST)
func handleOrders(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        // 获取所有订单
        mu.Lock()
        ordersCopy := make([]Order, len(orders)) // 创建副本以避免在序列化时持有锁
        copy(ordersCopy, orders)
        mu.Unlock()

        w.Header().Set("Content-Type", "application/json")
        if err := json.NewEncoder(w).Encode(ordersCopy); err != nil {
            http.Error(w, "编码JSON失败", http.StatusInternalServerError)
            return
        }

    case "POST":
        // 创建新订单
        var newOrder Order
        if err := json.NewDecoder(r.Body).Decode(&newOrder); err != nil {
            http.Error(w, "解析JSON请求体失败", http.StatusBadRequest)
            return
        }

        // 简单验证 (可以根据需要扩展)
        if newOrder.Name == "" || newOrder.Item == "" || newOrder.Price <= 0 {
            http.Error(w, "订单信息不完整或价格无效", http.StatusBadRequest)
            return
        }

        // 使用互斥锁保护共享资源
        mu.Lock()
        newOrder.ID = nextID
        nextID++
        orders = append(orders, newOrder)
        mu.Unlock()

        // 返回创建成功的状态和新订单数据
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusCreated) // 201 Created
        if err := json.NewEncoder(w).Encode(newOrder); err != nil {
            // 注意：这里即使写入响应体失败，订单也已创建。实际应用中可能需要更复杂的错误处理。
            log.Printf("编码新订单JSON失败: %v", err)
            return
        }

    default:
        // 不支持的HTTP方法
        http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
    }
}
